package example;

import java.io.*;
import java.nio.file.Files;
import java.util.Scanner;

public class Example3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径: ");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的内容: ");
        String word = scanner.next();
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()){
            System.out.println("搜索的路径不正确!");
            return;
        }
        searchByWord(rootFile,word);

    }

    private static void searchByWord(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for (File f: files) {
            System.out.println("当前遍历到: "+f.getAbsolutePath());
            if (f.isFile()){
                //在文件内容中搜索
            } else if (f.isDirectory()) {
                //是目录,递归遍历
                searchInFile(f,word);

            }else {
                ;
            }

        }
    }

    private static void searchInFile(File f, String word) {
        //通过这个方法在文件内部进行搜索
        //1.把文件内容读取出来.
        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if (n == -1){
                    break;
                }
                //需要将读出来的内容整体拼接到一起
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }
            System.out.println("[debug] 文件内容" + stringBuilder);
            //当循环结束后,StringBuilder就包含文件整个内容的字符串
            if (stringBuilder.indexOf(word) == -1){
                return;
            }
            //找到了,打印出文件的路径
            System.out.println("找到了"+word+"存在以"+f.getAbsolutePath());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
